package com.myssoteka.shared.dao;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.google.gwt.user.client.rpc.InvocationException;
import com.myssoteka.shared.domain.Book;
import com.myssoteka.shared.domain.User;

public class UserDao {

	protected UserDao() {}
	
	  private static class UserDaoHolder { 
	        private final static UserDao instance = new UserDao();
	    }
	 
	    public static UserDao getInstance() {
	        return UserDaoHolder.instance;
	    }
	    
	    public User getUserByUsername(String username){
	    	EntityManager em = null;
				try {
					em = EMFService.get().createEntityManager();				
					Query query = em.createQuery("select u from User u where username = :username");
					query.setParameter("username", username);
					User result = (User) query.getSingleResult();
					return result; 					
				} catch (NoResultException e) {
					return null;
				} catch (Exception e) {
					throw new InvocationException("Wystapil blad podczas wykonywania zdlanej uslugi", e);
				} finally {
					if (em != null) em.close();
				}
	    }
	    
		public void addUser(String username, String password) {
			EntityManager em = null;
			try {
				em = EMFService.get().createEntityManager();				
				User user = new User(username, password);
				em.persist(user);				
			} catch (Exception e) {
				throw new InvocationException("Wystapil blad podczas wykonywania zdlanej uslugi", e);				
			} finally {
				if (em != null) em.close();				
			}

		}

}
